<template>
  <div class="agile-kanban" v-if="currentPage === 1">
    <a-row style="margin: 0" :gutter="24">
      <a-col style="width: 328px; float: left">
        <label>看板名称：</label>
        <a-input
          style="width: calc(100% - 14px * 5)"
          v-model="searchParams.name"
          placeholder="请输入看板名称"
        ></a-input>
      </a-col>
      <a-col style="width: 328px; float: left">
        <label>标签：</label>
        <a-select
          style="width: calc(100% - 14px * 3)"
          mode="tags"
          v-model="searchParams.labels"
          placeholder="请选择标签"
        >
          <a-select-option v-for="val in labelList" :key="val.name">
            {{val.name}}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col style="width: 328px; float: left">
        <label>发布状态：</label>
        <a-select
          allowClear
          style="width: calc(100% - 14px * 5)"
          v-model="searchParams.status"
          placeholder="请选择发布状态"
        >
          <a-select-option :value="0">
            未发布
          </a-select-option>
          <a-select-option :value="1">
            已发布
          </a-select-option>
        </a-select>
      </a-col>
      <a-col style="width: 428px; float: left">
        <label>看板类型：</label>
        <a-button-group>
          <a-button @click="searchParams.type = undefined" :type="searchParams.type == undefined ? 'primary' : 'default'">
            全部
          </a-button>
          <a-button @click="searchParams.type = 1" :type="searchParams.type === 1 ? 'primary' : 'default'">
            我创建的
          </a-button>
          <a-button @click="searchParams.type = 2" :type="searchParams.type === 2 ? 'primary' : 'default'">
            我收藏的
          </a-button>
        </a-button-group>
      </a-col>
      <a-col style="width: 120px; float: left">
        <div style="display: flex">
          <a-button style="margin-left: auto;margin-right: 10px" @click="search"><b-svg type="search" />查询</a-button>
        </div>
      </a-col>
      <a-divider style="margin: 0" />
    </a-row>
    <a-row style="margin: 0" type="flex" :gutter="24">
      <a-col class="breadcrumb-container">
        <a-breadcrumb class="breadcrumb-style" style="width: 400px;margin-right: auto;float: left, padding: 12px 0">
          <a-breadcrumb-item v-for="(val, key) in breadcrumbList" :key="val.id">
            <span v-if="(key + 1) === breadcrumbList.length">{{val.name}}</span>
            <a v-else @click="breadcrumbClick(val.id)">{{val.name}}</a>
          </a-breadcrumb-item>
        </a-breadcrumb>
      </a-col>
      <a-col class="button-group">
        <a-button @click="newKanban"><b-svg type="doc"/>新建看板</a-button>
        <a-button @click="$refs.addCategory.show()"><b-svg type="folder"/>新建分类</a-button>
        <a-button @click="handleMove()"><b-svg type="move"/>移动到</a-button>
        <a-button @click="batchDel"><b-svg type="delete2"/>批量删除</a-button>
      </a-col>
    </a-row>
    <div class="page-content">
      <a-table
        bordered
        :rowKey="record => `${record.id}-${record.type}-${record.name}`"
        style="width: 100%"
        :scroll="{ x: '100%', y: 600 }"
        :row-selection="{ selectedRowKeys: table.selectedRowKeys, onChange: onSelectChange }"
        :columns="table.columns"
        :data-source="table.data"
        :loading="table.loading"
        :pagination="table.pagination"
      >
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleMove(record)"><b-svg type="move"/>移动</a-button>
          <a-button type="link" @click="renameClick(record)" >
            <b-svg type="rename"/>重命名
          </a-button>
          <a-button type="link" @click="delListItem(record)"><b-svg type="delete2"/>删除</a-button>
          <a-popover
            trigger="click"
            v-if="record.type === 2"
          >
            <div slot="content">
              <a class="popover-button" @click="handlePreview(record.id)"><b-svg class="icon" type="preview"></b-svg>预览</a>
              <a class="popover-button" @click="collect(record.id)"><b-svg class="icon" type="preview"></b-svg>收藏</a>
              <a class="popover-button"
                v-if="record.status != 1"
                @click="kanBanOnlineOrOffline(record, 1)"
              ><b-svg class="icon" type="on-line"></b-svg>申请上线</a>
              <a class="popover-button"
                v-else
                @click="kanBanOnlineOrOffline(record, 0)"
              ><b-svg class="icon" type="off-line"></b-svg>申请下线</a>
              <a class="popover-button" @click="showRecords(record)"><b-svg class="icon" type="record"></b-svg>申请记录</a>
            </div>
            <a-button type="link" ><b-svg type="ellipsis"></b-svg></a-button>
          </a-popover>
        </template>
      </a-table>
    </div>
    <add-category @ok="handleAddCategory" ref="addCategory"/>
    <AddBoard ref="kanban" @ok="handleAddKanban"  @edit="handleEdit"  />
    <move-place
      @reset="reset"
      @refresh="search"
      @move="handleMoveSuccess"
      ref="movePlace"
    ></move-place>
    <!-- <Rename ref="rename" /> -->
  </div>
  <application-record
    @retreat="currentPage = 1"
    v-else-if="currentPage === 2"
    :data="activeItem"
  />
  <!-- <AddAgileKanban v-else-if="currentPage === 3"/> -->

</template>

<script>
import AddCategory from "./AddCategory"
import AddBoard from "./AddBoard"
// import Rename from "./Rename"
import MovePlace from "./MovePlace"
import ApplicationRecord from "./ApplicationRecord"
// import AddAgileKanban from "./AddAgileKanban/AddAgileKanban"
import { reset } from "../BoardEdit/LowCode/lib/utils"
import {
  getCategoryAndDashboardListByPid,
  batchDelDashboardCategory,
  batchDelDashboard,
  kanBanOnlineOrOffline,
  labelTop20,
  applyStore,
  upDashboard
} from "@/api/multidimensionalAnalysis"

export default {
  components: {
    AddBoard,
    MovePlace,
    AddCategory,
    ApplicationRecord,
    // Rename,
    // AddAgileKanban
  },
  data() {
    return {
      currentPage: 1,
      activeItem: {},
      labelList: [],
      searchParams: {
        current: 1,
        size: 20,
        name: "",
        status: undefined,
        type: undefined,
        labels: [],
        pid: 0
      },
      breadcrumbList: [
        {
          id: 0,
          name: "全部面板"
        }
      ],
      affixed: false,
      listType: "card",
      table: {
        selectedRowKeys: [],
        columns: [
          {
            title: "序号",
            width: 60,
            fixed: "left",
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            dataIndex: "name",
            title: "名称",
            width: 200,
            customRender: (text, record, index) => {
              let icon
              const style = {
                marginRight: "4px",
                fontSize: "16px"
              }
              const click = () => {
                this.nameClick(record)
              }
              if (record.type === 1) {
                icon = <Svg type="folder" style={style}/>
              } else if(record.type === 2) (
                icon = <Svg type="doc" style={style}/>
              )
              return <a onclick={click}>{icon}{text}</a>
            },
          },
          // {
          //   dataIndex: 'describe',
          //   width: 200,
          //   title: '描述',
          // },
          {
            dataIndex: "description",
            title: "描述",
            width: 200,
          },
          {
            dataIndex: "labels",
            title: "标签",
            width: 100,
            customRender: (text, record, index) => {
              if (record.labels) {
                return <div>
                {
                    record.labels.map(val => <span>{val}</span>)
                }
                </div>
              }
            },
          },
          {
            dataIndex: "status",
            title: "发布状态",
            width: 120,
            customRender: (text, record, index) => {
              if (text === 1) {
                return "已发布"
              }
              else {
                return "未发布"
              }
            },
          },
          {
            dataIndex: "createTime",
            title: "创建时间",
            width: 160,
          },
          {
            dataIndex: "createUser",
            title: "创建人",
            width: 120,
          },
          {
            dataIndex: "updateTime",
            title: "修改时间",
            width: 160,
          },
          {
            dataIndex: "updateUser",
            title: "修改人",
            width: 120,
          },
          {
            key: "action",
            title: "操作",
            width: 300,
            fixed: "right",
            scopedSlots: { customRender: "action" }
          },
        ],
        data: [],
        loading: false,
        pagination: {
          // hideOnSinglePage: true,
          pageSize: 20, // 默认每页显示数量
          showSizeChanger: true, // 显示可改变每页数量
          pageSizeOptions: ["20", "50", "100"], // 每页数量选项
          showTotal: (total) => `共${total}条`, // 显示总数
          onShowSizeChange: this.pageChange, // 改变每页数量时更新显示
          onChange: this.pageChange, // 点击页码事件
          total: 0, // 总条数
          current: 1,
        }
      },
      tree:{
        searchValue:null,
        autoExpandParent: true,
        defaultExpandAll:true,
        replaceFields: {
          title: "name",
          value: "key",
        },
        selectedKeys: [],
        expandedKeys: [],
        treeDataList: [],
        loadedKeys: [],
      },
    }
  },
  created() {
    reset()
    this.search()
    this.getLabelTop20()
  },
  methods: {
    handleAddCategory(){
      this.search()
    },
    handleAddKanban(val){
      console.log(val)
      // this.currentPage = 3
      // this.$router.push({ path: "/board/boardPreview", query: {id} })
    },
    handlePreview(id){
      this.$router.push({ path: "/board/boardPreview", query: {id} })
    },
    reset() {
      this.searchParams.pid = 0
      this.breadcrumbList = [
        {
          id: 0,
          name: "全部面板"
        }
      ]
      this.search()
    },
    search() {
      const params = {
        ...this.searchParams,
        labels: this.searchParams.labels.join(",")
      }
      this.table.loading = true
      getCategoryAndDashboardListByPid(params)
      .then(res => {
        if (res.errorCode === 0) {
          const pid = this.breadcrumbList[this.breadcrumbList.length - 1].id
          this.table.data = res.data.records.map(val => {
            if (val.type === 1 && pid !== 0) {
              val.pid = pid
            }
            return val
          })
          const { current, size, total } = res.data
          Object.assign(this.table.pagination, {
            pageSize: size,
            total,
            current
          })
        } else {
          this.$message.error(res.msg)
        }
        this.table.loading = false
      })
      .catch(err => {
        this.table.loading = false
        this.$message.error(err)
      })
    },
    collect(id) {
      applyStore(id)
      .then(res => {
        if (res.errorCode === 0) {
          this.search()
          this.$message.success("申请收藏成功")
        } else {
          this.$message.error(res.msg)
        }
      })
      .catch(err => {
        this.$message.error(err.response.data.message)
      })
    },
    getLabelTop20() {
      labelTop20()
      .then(res => {
        if (res.errorCode === 0) {
          this.labelList = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
      .catch(err => {
        this.$message.error(err)
      })
    },
    showRecords(val) {
      this.activeItem = val
      this.currentPage = 2
    },
    renameClick(val) {
      console.log(val)
      if (val.type === 1) {
        this.$refs.addCategory.show(val)
      } else if (val.type === 2) {
        // this.$refs.rename.show(val)
        this.$refs.kanban.show(val, "edit")
      }
    },
    breadcrumbClick(id){
      this.searchParams = {
        current: 1,
        size: 20,
        name: "",
        status: undefined,
        type: undefined,
        labels: [],
        pid: id
      }
      this.search()
      const index = this.breadcrumbList.findIndex(val => val.id === id)
      if (index > -1) {
        this.breadcrumbList = this.breadcrumbList.slice(0, index + 1)
      }
    },
    nameClick(val) {
      if(val.type === 1){
        this.searchParams = {
          current: 1,
          size: 20,
          name: "",
          status: undefined,
          type: undefined,
          labels: [],
          pid: val.id
        }
        this.breadcrumbList.push({
          id: val.id,
          name: val.name,
          data: val
        })
        this.search()
      }
      else if(val.type === 2){
        // localStorage.setItem('addKanbanId',val.id)
        // console.log(this.$router)
        this.$router.push({ path: "/board/boardEdit", query: {id: val.id} })
        // window.open(`/multidimensionalAnalysis/editAgileKanban?id=${val.id}`, '_blank')
      }

    },
    pageChange(current, size) {
      Object.assign(this.searchParams, {
        current,
        size
      })
      this.search()
    },
    kanBanOnlineOrOffline(val, status) {
      const params = new FormData()
      params.append("id", val.id)
      params.append("status", status)

      kanBanOnlineOrOffline(params)
      .then(res => {
        if (res.errorCode === 0) {
          this.$message.success(res.msg)
          this.search()
        } else {
          this.$message.error(res.msg)
        }
      })
      .catch(err => {
        this.$message.error(err)
      })
    },
    // 看板分类批量删除
    batchDelDashboardCategory(params) {
      params.forEach(item => {
        if(typeof item.labels === "string"){
          item.labels = item.labels.split(",")
        }

      })
      return new Promise((resolve, reject) => {
        batchDelDashboardCategory(params)
        .then(res => {
          if (res.errorCode === 0) {
            resolve()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          reject()
          this.$message.error(err)
        })
      })
    },
    batchDelDashboard(params) {
      return new Promise((resolve, reject) => {
        batchDelDashboard(params)
        .then(res => {
          if (res.errorCode === 0) {
            resolve()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          reject()
          this.$message.error(err)
        })
      })
    },
    onSelectChange(val) {
      this.table.selectedRowKeys = val
      console.log(val)
    },
    batchDel() {
      if (!this.table.selectedRowKeys || this.table.selectedRowKeys.length === 0) {
        this.$message.warning("请选择删除项")
        return
      }
      this.$confirm({
        title: "确定删除吗?",
        onOk:() => {

          // let num = 0
          // const callBack = () => {
          //   num++
          //   if (num === 1) {
          //     this.$message.success('删除成功')
          //     this.search()
          //   }
          // }
          const {
            ids,
            categoryIds
          } = this.getIds()

          const params1 = this.table.data.filter(val => categoryIds.includes(String(val.id)))
          const apiList = []
          if(params1.length > 0){
            apiList.push({callback: this.batchDelDashboardCategory, params: params1})

            // .then(callBack)
            // .catch(callBack)
          }
          if(ids.length > 0){
            const params2 = new FormData()
            params2.append("ids", ids.join(","))
            // this.batchDelDashboard(params2)
            apiList.push({callback: this.batchDelDashboard, params: params2})
            // .then(callBack)
            // .catch(callBack)
          }
          Promise.all(apiList.map(api => api.callback(api.params)))
          .then(()=> {
            this.$message.success("删除成功")
            this.search()
          })
          .catch(()=> {

          })

        },
        onCancel() {},
      })
    },
    delListItem(val) {
      this.$confirm({
        title: "确定删除吗?",
        onOk:()=> {
          if (val.type === 1) {
            this.batchDelDashboardCategory([val])
            .then(() => {
              this.search()
            })
          } else if (val.type === 2) {
            const params = new FormData()
            params.append("ids", val.id)
            this.batchDelDashboard(params)
            .then(() => {
              this.search()
            })
          }
        },
        onCancel() {},
      })
    },
    newKanban() {
      console.log("我执行了")
      this.$refs.kanban.show()
    },
    onLoadData() {
      return new Promise((resolve, reject) => {
        resolve()
      })
    },
    treeExpand(expandedKeys) {
      this.tree.expandedKeys = expandedKeys

    },
    handleEdit(){
      this.search()
    },
    handleMove(data){
      let list = []
      // 移动单个
      if(data){
        list = [data]
      }
      // 批量移动
      else {
        if (!this.table.selectedRowKeys || this.table.selectedRowKeys.length === 0) {
          this.$message.warning("请选择删除项")
          return
        }
        const {
          ids,
          categoryIds
        } = this.getIds()
        const isList = [...ids, ... categoryIds].map(id => Number(id))
        list = this.table.data.filter(item => isList.includes(item.id))
      }
      this.$refs.movePlace.show(list, true)
    },
    getIds(){
      const ids = []
      const categoryIds = []
      this.table.selectedRowKeys.forEach(val => {
        const arr = val.split("-")
        const type = arr[1]
        if (type === "1") {
          categoryIds.push(arr[0])
        } else if (type === "2") {
          ids.push(arr[0])
        }
      })
      return {
        ids,
        categoryIds
      }
    },
    handleMoveSuccess(){
      this.search()
    }

  }
}
</script>

<style lang="less" scoped>
.agile-kanban{
  background: #ffffff;
  // padding: 10px 12px;
  border-radius: 4px;
  .page-content{
    display: flex;
    flex-direction: column;
    height: calc(100% - 53px);
    margin-left: 12px;
    margin-right: 12px;
    .breadcrumb-style{
      padding: 6px 0;
    }
  }
}
@media (max-width: 1200px) {
  .breadcrumb-container{
    width: 100%!important;
    order: 2;
  }
  .button-group{
    width: 100%!important;
    order: 1;
  }
}
.breadcrumb-container{
  width: calc(100% - 464px);
  float: left;
  display: flex;
  align-items: center;
  white-space: nowrap; /* 规定文本是否折行 */
  overflow: hidden; /* 规定超出内容宽度的元素隐藏 */
  text-overflow: ellipsis;
}
.button-group{
  width: 464px;
  float: left;
  display: flex;
  flex-wrap: wrap;
  button:nth-child(1) {
    // margin-left: auto;
  }
  button:not(:last-child){
    margin-right: 10px;
  }
}
.popover-button{
  display: block !important;
  line-height: 32px;
  font-weight: 400;
  white-space: nowrap;
  text-align: center;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  user-select: none;
  touch-action: manipulation;
  height: 32px;
  // padding: 0 15px;
  padding: 0 6px;
  font-size: 14px;
  background-color: #fff;
  text-align: left;
  .icon{
    margin-right: 4px;
  }
  &:hover{
    background: #1890ff;
    color: #ffffff;
  }
}
/deep/ .ant-col{
  margin: 10px 0;
  padding: 0 12px;
}
</style>
